package 代码随想录.数组;

import java.util.Arrays;

public class a59螺旋矩阵2 {
    static class Solution {
        public int[][] generateMatrix0(int n) {
            int cnt = 1;
            int[][] matrix = new int[n][n];
            if (n == 1) {
                matrix[0][0] = 1;
                return matrix;
            }
            int x = 0;
            int y = 0;
            int loop = 1;
            while (loop <= n / 2) {
                int i = x;
                int j = y;
                while (j < n - loop) {
                    matrix[i][j++] = cnt++;
                }
                while (i < n - loop) {
                    matrix[i++][j] = cnt++;
                }
                while (j > y) {
                    matrix[i][j--] = cnt++;
                }
                while (i > x) {
                    matrix[i--][j] = cnt++;
                }
                loop++;
                x++;
                y++;
            }
            if (n % 2 == 1) {
                matrix[n / 2][n / 2] = cnt;
            }
            return matrix;
        }

        public int[][] generateMatrix(int n) {
            int[][] matrix = new int[n][n];
            int left = 0, right = n - 1, top = 0, bottom = n - 1;
            int cnt = 1;
            while (cnt <= n * n) {
                for (int i = left; i <= right; i++) {
                    matrix[top][i] = cnt++;
                }
                top++;
                for (int i = top; i <= bottom; i++) {
                    matrix[i][right] = cnt++;
                }
                right--;
                for (int i = right; i >= left; i--) {
                    matrix[bottom][i] = cnt++;
                }
                bottom--;
                for (int i = bottom; i >= top; i--) {
                    matrix[i][left] = cnt++;
                }
                left++;
            }
            return matrix;
        }

        public static void main(String[] args) {
            Solution solution = new Solution();
            int[][] matrix = solution.generateMatrix(5);
            for (int[] ints : matrix) {
                System.out.println(Arrays.toString(ints));
            }
        }
    }
}